//
//  CollectViewController.m
//  BTRIP
//
//  Created by Rain on 15/11/17.
//  Copyright © 2015年 johnbk. All rights reserved.
//

#import "CollectViewController.h"
#import "CollectTableViewCell.h"
#import "CoreDataManager.h"
#import "CollectTravelModel.h"
#import "FoodShopCollectModel.h"
#import "SpecialDetailViewController.h"
#import "SQLDataManager.h"
#import "DetailGoodShopViewController.h"

@interface CollectViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) UISegmentedControl *segmentedControl;

@property (nonatomic, retain) NSMutableArray *resultArray;

@property (nonatomic, retain) CoreDataManager *coreDataManager;

@property (nonatomic, retain) UIButton *clearButton;

@property (nonatomic, retain) SQLDataManager *dataManager;

@end

@implementation CollectViewController

- (void)dealloc {
    [_dataManager release];
    [_tableView release];
    [_segmentedControl release];
    [_resultArray release];
    [_coreDataManager release];
    
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController.navigationBar setHidden:NO];

    
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        [self dataload_CollectTravel];
    } else {
        [self dataload_CollectFood];
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.dataManager = [SQLDataManager shareSQLDataManager];
    
    self.coreDataManager = [CoreDataManager shareManager];
    NSLog(@"url: %@", [_coreDataManager applicationDocumentsDirectory]);
    self.resultArray = [NSMutableArray array];
    
    [self createUI_Collect];
    
}

- (void)dataload_CollectTravel {
    
    [self.resultArray removeAllObjects];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"CollectTravelModel"];
    
    NSArray *fetchedObjects = [_coreDataManager.managedObjectContext executeFetchRequest:fetchRequest error:nil];
    NSLog(@"🍎%ld", fetchedObjects.count);
    
    self.resultArray = [NSMutableArray arrayWithArray:fetchedObjects];
    [self.tableView reloadData];
    
}

- (void)dataload_CollectFood {
    
    [self.resultArray removeAllObjects];
    [_dataManager open];
    NSArray *array = [[SQLDataManager shareSQLDataManager] searchTitle];
    self.resultArray = [NSMutableArray arrayWithArray:array];
    [_dataManager close];
    [self.tableView reloadData];
}


- (void)createUI_Collect {
    
    self.segmentedControl = [[UISegmentedControl alloc] initWithItems:@[@"旅行", @"美食"]];
    self.segmentedControl.frame = CGRectMake(10 * SWIDTH, 64 * SWIDTH, KWIDTH - 20 * SWIDTH, 30 * SWIDTH);
    self.segmentedControl.backgroundColor = [UIColor whiteColor];
    self.segmentedControl.tintColor = [UIColor lightGrayColor];
    self.segmentedControl.selectedSegmentIndex = 0;
    [self.segmentedControl addTarget:self action:@selector(segmentedControlAction) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.segmentedControl];
    [self.segmentedControl release];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 94 * SWIDTH, KWIDTH, KHEIGHT - 94 * SWIDTH) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    [self.tableView release];
    
    [self.tableView registerClass:[CollectTableViewCell class] forCellReuseIdentifier:@"collectCell"];
    
    self.clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.clearButton.frame = CGRectMake(0, 0, 50 * SWIDTH, 30 * SWIDTH);
    [self.clearButton setTitle:@"清空" forState:UIControlStateNormal];
    [self.clearButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.clearButton addTarget:self action:@selector(clearButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:_clearButton];
    [self.navigationItem.rightBarButtonItem release];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _resultArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CollectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"collectCell" forIndexPath:indexPath];
    cell.collectTravelModel = _resultArray[indexPath.row];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 220 * SWIDTH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        SpecialDetailViewController *detailVC = [[SpecialDetailViewController alloc] init];
        detailVC.urlStr = [_resultArray[indexPath.row] theUrl];
        [self.navigationController pushViewController:detailVC animated:YES];
        [detailVC release];
    } else {
        DetailGoodShopViewController *detailGoodShopVC = [[DetailGoodShopViewController alloc] init];
        detailGoodShopVC.idOfUrl = [_resultArray[indexPath.row] theUrl];
        [self.navigationController pushViewController:detailGoodShopVC animated:YES];
        [detailGoodShopVC release];
    }
    
}

#pragma mark tableView编辑状态
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
    NSLog(@"进入编辑状态");
    [self.tableView setEditing:YES animated:YES];
}

#pragma mark 指定某行是否可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

#pragma mark 编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

#pragma mark 编辑实现
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (self.segmentedControl.selectedSegmentIndex == 0) {
            CollectTravelModel *modelDel = _resultArray[indexPath.row];
            
            [_coreDataManager.managedObjectContext deleteObject:modelDel];
            [_coreDataManager saveContext];
            
            [self.resultArray removeObjectAtIndex:indexPath.row];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        } else {
            FoodShopCollectModel *model = _resultArray[indexPath.row];
            [_dataManager open];
            [_dataManager deleteInfo:model.name];
            
            [self.resultArray removeObjectAtIndex:indexPath.row];
            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
        
    }
}

- (void)segmentedControlAction {
    
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        [self dataload_CollectTravel];
    } else {
        [self dataload_CollectFood];
    }
    
}


#pragma mark 清空按钮
- (void)clearButtonAction {
    
    if (self.segmentedControl.selectedSegmentIndex == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"清空所有收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *decideAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            for (CollectTravelModel *modelDel in _resultArray) {
                [_coreDataManager.managedObjectContext deleteObject:modelDel];
            }
            [_coreDataManager saveContext];
            
            [_resultArray removeAllObjects];
            [_tableView reloadData];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        [alert addAction:decideAction];
        [self presentViewController:alert animated:YES completion:nil];
    } else if (self.segmentedControl.selectedSegmentIndex == 1) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"清空所有收藏" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *decideAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            for (CollectTravelModel *modelDel in _resultArray) {
                
                [_dataManager open];
                [_dataManager deleteInfo:modelDel.name];
                
            }
            
            [_resultArray removeAllObjects];
            [_tableView reloadData];
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:cancelAction];
        [alert addAction:decideAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [_dataManager close];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
